<template>
  <a-card class="general-card" title="品牌列表" :bordered="false">
    <PickSearchColumn :columns="columnsSearch" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}">
    </PickSearchColumn>
    <a-space style="margin-bottom: 16px">
      <a-button @click="handleAdd" type="primary">添加</a-button>
    </a-space>
    <PickTablePage ref="tablePageRef" :columns="columnsTable" :methods="sortMethods" :api="getGoodsBrand"
      @delete="handleDelete" @editor="handleEdit" :api-params="apiParams" :bordered="true">
      <template #logo="{ data }">
        <a-image width="50" height="50" :src="data.logo" />
      </template>
      <template #btnList="{ data }">
        <a-space>
          <a-button v-if="data?.deleteFlag == 0" type="text" status="danger" @click="handleDisabled(data)">
            禁用</a-button>
          <a-button v-else  @click="handleEnable(data)" type="text" status="success">启用</a-button>
        </a-space>
      </template>
    </PickTablePage>
    <!-- 添加modal -->
    <a-modal v-model:visible="brandData.enableAddModal" :align-center="false" :footer="false">
      <template #title> {{ title }} </template>
      <a-form ref="formRef" :model="brandData.form" @submit="handleAddOk">
        <a-form-item field="name" label="品牌名称" :rules="[REQUIRED, VARCHAR20]" :validate-trigger="['change']">
          <a-input v-model="brandData.form.name" />
        </a-form-item>
        <a-form-item field="logo" label="品牌图标" :rules="[REQUIRED]" :validate-trigger="['change']" validate-phone>
          <a-input v-model="brandData.form.logo" />
          <a-tooltip>
            <a-button><icon-eye /></a-button>
            <template #content>
              <div>
                <img :src="brandData.form.logo" alt="该资源不存在" style="width: 100%; margin: 0 auto" />
                <a style="margin-top: 5px; text-align: right; cursor: pointer" @click="viewImage = true">查看大图</a>
              </div>
            </template>
          </a-tooltip>
          <a-button type="primary" @click="hanlderUpload">上传图片</a-button>
        </a-form-item>
        <a-form-item label="操作">
          <a-button :loading="brandData.formLoading" html-type="submit" type="primary">保存</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
  <!--<a-modal v-model:visible="ossvisible" :width="1100">-->
    <!--<ossManage :close-model="handleOssOk" @changOssImage="changOssImage"></ossManage>-->
  <!--</a-modal>-->
  <a-modal v-model:visible="showOssManager" :width="1100"  @ok="handleOss" title="oss资源管理" @cancel="showOssManager = false">
    <ossManages @selected="changOssImage" :isSingle="true"></ossManages>
  </a-modal>

  <a-modal v-model:visible="viewImage" :width="1100" @ok="handleOssOk" @cancel="handleOssCancel">
    <img :src="brandData.form.logo" alt="该资源不存在" style="width: 100%; margin: 0 auto; display: block" />
    <template #footer>
      <div style="text-align: right">
        <a-button type="text" status="danger" @click="viewImage = false">关闭</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="ts">

import { PickSearchColumn, PickTablePage } from '@pickmall/ui-v3-components';
import { MethodsRule, ColumnsDataRule, SearchRule } from '@/types/global';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { REQUIRED, VARCHAR20 } from '@/utils/validator';
import {
  getGoodsBrand,
  delBrand,
  addBrand,
  updateBrand,
  disableBrand,
} from '@/api/goods';
import { deleteFlagStatus } from '@/utils/tools';
import { ref, reactive } from 'vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { Message } from '@arco-design/web-vue';
import ossManage from '@/views/setting/oss-manage/index.vue';
import ossManages from '@/components/oss-manage/index.vue';

const apiParams = ref({});
const viewImage = ref<boolean>(false);
const tablePageRef = ref<any>();
const title = ref<string>('');
const ossvisible = ref<boolean>(false);
const showOssManager = ref<boolean>(false); // oss弹框
const selectedSku = ref(); // 选择的sku
// 获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
const formRef = ref<FormInstance>();
// const
interface formInterface {
  enableAddModal: boolean;
  formLoading: boolean;
  fid: string | number;
  form: {
    name: string;
    logo: string;
    [key:string]: any;
  };
  [key:string]: any;
}
const columnsSearch: Array<SearchRule> = [
  {
    label: '品牌名称',
    model: 'name',
    disabled: false,
    input: true,
  },
];

const columnsTable: ColumnsDataRule[] = [
  {
    title: '品牌名称',
    dataIndex: 'name',
    width: 150,
  },
  {
    title: '品牌图标',
    dataIndex: 'logo',
    width: 150,
    slot: true,
    slotTemplate: 'logo',
  },

  {
    title: '状态',
    dataIndex: 'deleteFlag',
    width: 150,
    slot: true,
    slotData: {
      badge: deleteFlagStatus,
    },
  },
];

const sortMethods: MethodsRule = {
  title: '操作',
  width: 250,
  fixed: 'right',
  methods: [
    {
      title: '编辑',
      callback: 'editor',
      type:"text" ,
      status:"warning"
    },
    {
      // title: '禁用',
      // callback: 'disabled',
      slot: true,
      slotTemplate: 'btnList',
    },
    {
      title: '删除',
      callback: 'delete',
      type:"text" ,
      status:"danger"
    },
  ],
};
// 数据集
const brandData = reactive<formInterface>({
  enableAddModal: false,
  formLoading: false,
  fid: '', // 当前form的ids
  form: {
    name: '',
    logo: '',
  }, // 表单提交数据
});
// 点击添加
function handleAdd() {
  brandData.enableAddModal = true;
  title.value = '添加';
  brandData.fid = '';
  Object.keys(brandData.form).forEach((key) => {
    brandData.form[key] = '';
  });
}
// 添加/修改地址
async function handleAddOk() {
  // brandData.form.password = this.md5(brandData.form.password);
  const auth = await formRef.value?.validate();
  if (!auth) {
    let res;
    !brandData.fid
      ? (res = await addBrand(brandData.form))
      : (res = await updateBrand(brandData.fid, brandData.form));

    if (res.data.success) {
      Message.success(`${brandData.fid ? '修改' : '添加'}成功!`);
      brandData.enableAddModal = false;
      tablePageRef.value.init();
    }
  }
}
// 点击修改地址
function handleEdit(val: any) {
  title.value = '编辑';
  if (val) {
    Object.keys(val.record).forEach((key) => {
      // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
      brandData.form.hasOwnProperty(key)
        ? (brandData.form[key] = val.record[key])
        : '';
    });
    brandData.fid = val.record.id;
    brandData.enableAddModal = true;
  }
}
// 回调删除
function handleDelete(data: any) {
  modal.confirm({
    title: '确认删除',
    content: `您确认要删除${data.record.name}品牌?`,
    alignCenter: false,
    onOk: async () => {
      const res = await delBrand(data.record.id);
      if (res.data.success) {
        Message.success('品牌删除成功');
        tablePageRef.value.init();
      }
    },
  });
}
// 回调禁用
function handleDisabled(data: any) {
  console.log(data, 'data');
  modal.confirm({
    title: '确认禁用',
    content: `您确认要禁用品牌${data.name}品牌?`,
    alignCenter: false,
    onOk: async () => {
      const res = await disableBrand(data.id, { disable: true });
      if (res.data.success) {
        Message.success('操作成功');
        tablePageRef.value.init();
      }
    },
  });
}
// 回调启用
function handleEnable(data: any) {
  modal.confirm({
    title: '确认启用',
    content: `您确认要启用品牌${data.name}品牌?`,
    alignCenter: false,
    onOk: async () => {
      const res = await disableBrand(data.id, { disable: false });
      if (res.data.success) {
        Message.success('操作成功');
        tablePageRef.value.init();
      }
    },
  });
}
// 图片 url
// const changOssImage = (e: any) => {
//   brandData.form.logo = e;
// };
// 关闭oss弹框
const handleOssOk = (e: any) => {
  // ossvisible.value = false;
  showOssManager.value= false;
};
const handleOssCancel = (e: any) => {
  // ossvisible.value = false;
  showOssManager.value = false;
};
// 上传图片
const hanlderUpload = () => {
  // ossvisible.value = true;
  showOssManager.value = true;
};
// oss资源确定
const handleOss = () => {
  showOssManager.value = false;
  brandData.form.logo = selectedSku.value[selectedSku.value.length-1].url;
};
// oss资源改变
const changOssImage = (val: any) => {
  selectedSku.value = [];
  val.forEach((item: any)=>{
    selectedSku.value.push({url:item.url})
  })
};




</script>
